import React, {PropsWithChildren, useCallback, useEffect, useRef, useState} from 'react'
import {Text, View} from "@tarojs/components";
import styles from "./employeeOperateRecords.module.sass"
import {getEmployeeSummaries} from "../apis/EmployeeApi";
import {PAGE_START, Pageable} from "../utils/Page";
import {QueryEmployeeOperateRecordResponse, queryEmployeeOperateRecords} from "../apis/EmployeeOperateRecordApi";
import {
    Calendar,
    Cell, Menu,
    MenuItem,
    VirtualList
} from "@nutui/nutui-react-taro";
import {NumberIdAndName} from "../types/BasicModels";
import {LocalDate} from "@js-joda/core";
import {DATE_WITH_TIME_FORMATER, YEAR_MONTH_DAY_INTERNATIONAL_FORMATER} from "../utils/Date";
import MyNavigationBar from "../components/MyNavigationBar";

export interface EmployeeOperateRecordsProps extends PropsWithChildren {

}

const EmployeeOperateRecords: React.FC<EmployeeOperateRecordsProps> = ({}) => {
    const [loading, setLoading] = useState(false)
    const [data, setData] = useState<QueryEmployeeOperateRecordResponse[]>([])
    const [pageable, setPageable] = useState(new Pageable(PAGE_START, 20))
    const [last, setLast] = useState(true)
    const [employeeId, setEmployeeId] = useState<number>()
    const [dateRange, setDateRange] = useState<[string, string | undefined]>()
    const query = useCallback(() => {
        setLoading(true)
        queryEmployeeOperateRecords({
            createdStartDate:dateRange?dateRange[0]:undefined,
            createdEndDate:dateRange?dateRange[1]:undefined,
            operatorIds:employeeId?[employeeId]:undefined,
        }, pageable,).then(res => {
            setData(data.concat(res.data.content))
            setLast(res.data.last)
        }).finally(() => {
            setLoading(false)
        })
    }, [...pageable.toDependencyList(), employeeId, ...(dateRange ?? [undefined, undefined])]);
    const [employees, setEmployees] = useState<NumberIdAndName[]>([])
    useEffect(() => {
        getEmployeeSummaries().then(response => {
            setEmployees(response.data)
        })
    }, []);

    useEffect(() => {
        onSearch()
    }, [employeeId, ...(dateRange ?? [undefined, undefined])]);

    function onSearch() {
        setData([])
        setLast(true)
        setPageable(new Pageable(PAGE_START, 20))
    }

    useEffect(() => {
        query()
    }, [query]);

    const dateMenuItemRef = useRef()
    const [visible, setVisible] = useState(false)

    return <>
        <MyNavigationBar>操作日志</MyNavigationBar>
        {// @ts-ignore
            <Calendar type={"range"} popup={true} visible={visible} endDate={LocalDate.now().format(YEAR_MONTH_DAY_INTERNATIONAL_FORMATER)} startDate={LocalDate.now().minusMonths(1).format(YEAR_MONTH_DAY_INTERNATIONAL_FORMATER)} onConfirm={(param:string[string[]]) => {
                function toDateString(d:string[]) {
                    return d[0] + "-" + d[1] + "-" + d[2]
                }
                setDateRange([toDateString(param[0]),toDateString(param[1])]);
                (dateMenuItemRef.current as any)?.toggle(false)
            }} onClose={()=>{
                (dateMenuItemRef.current as any)?.toggle(false)
                setVisible(false)
            }}/>
        }
        <View className={styles.container}>
            <Menu onOpen={index => {
                if (index === 1) {
                    setVisible(true)
                }
            }}
                  onClose={index => {
                      if (index === 1) {
                          setVisible(false)
                      }
                  }}
            >
                <MenuItem
                    value={employeeId}
                    // @ts-ignore
                    options={[{text: "全部人员", value: undefined,}, ...employees.map(e => ({
                        text: e.name,
                        value: e.id
                    }))]}
                    onChange={v => {
                        onSearch()
                        setEmployeeId(v.value);
                    }}/>
                <MenuItem title={dateRange?`${dateRange[0]}至${dateRange[1]}`:"日期"} ref={dateMenuItemRef}>
                    <View></View>

                </MenuItem>

            </Menu>

            <VirtualList className={styles.scrollView}
                         onScroll={() => {
                             if (!last && !loading) {
                                 setPageable(pageable.next)
                             }
                         }}
                         itemHeight={88}
                         itemEqual={false}
                         list={data}
                         itemRender={(record: QueryEmployeeOperateRecordResponse) => {
                             return <Cell style={{margin: 0}}
                                          key={record.id}
                                          title={<View>
                                              {record.content.map((item,index)=><Text key={index} className={(()=>{
                                                  if (item.resource){
                                                      return styles.link
                                                  }else if (item.highlight){
                                                      return styles.highlight
                                                  }else {
                                                      return ""
                                                  }
                                              })()}>{item.text}</Text>)}
                                          </View>}
                                          description={`${record.createdBy.name}  -  ${record.createdDateTime.format(DATE_WITH_TIME_FORMATER)}`}/>;
                         }}/>
        </View>
    </>
}

export default EmployeeOperateRecords


